package com.example.ymm.modules1.service.impl.hl.ex;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.ex.ExPublishGroup;
import com.example.ymm.modules1.entity.hl.ex.ExUserAnser;
import com.example.ymm.modules1.entity.hl.ex.ExUserGroup;
import com.example.ymm.modules1.mapper.ex.ExUserGroupMapper;
import com.example.ymm.modules1.query.hl.ex.ExUserAnserQueryCriteria;
import com.example.ymm.modules1.query.hl.ex.ExUserGroupQueryCriteria;
import com.example.ymm.modules1.service.dto.heng.ex.UserGroupIngDto;
import com.example.ymm.modules1.service.hl.ex.ExPublishGroupService;
import com.example.ymm.modules1.service.hl.ex.ExPublishPaperService;
import com.example.ymm.modules1.service.hl.ex.ExUserAnserService;
import com.example.ymm.modules1.service.hl.ex.ExUserGroupService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@DS("slave2")
public class ExUserGroupServiceImpl extends BaseServiceImpl<ExUserGroupMapper, ExUserGroup> implements ExUserGroupService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    ExPublishGroupService exPublishGroupService;

    @Autowired
    ExPublishPaperService exPublishPaperService;
    @Autowired
    ExUserAnserService exUserAnserService;

    @Override
    public TableList<ExUserGroup> list(ExUserGroupQueryCriteria criteria, YmPageDto pageDto) {
        IPage<ExUserGroup> page = new Page<ExUserGroup>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExUserGroup.class, criteria);
        predicate.orderByAsc("sort");
        baseMapper.selectPage(page, predicate);
        TableList<ExUserGroup> tableList=new TableList(page);
        return tableList;
    }

    public List<ExUserGroup> queryAll(ExUserGroupQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(ExUserGroup.class, criteria);
        predicate.orderByAsc("sort");
        List<ExUserGroup> result =baseMapper.selectList(predicate);
        return result;
    }

    //判断是否到达关闭时间,到达时间后关闭
    @Override
    public Integer izGoTimeUserGroup(List<ExUserGroup> exUserGroups,boolean isSubmit) {

        //是否到达了关闭时间
        UserGroupIngDto userGroupIngDto = izArriveEndTime(exUserGroups);

        Integer index=null;

        if(userGroupIngDto.getIng_index()!=null){

            //到达时间的下标
            if(userGroupIngDto.getResult_index()!=null){
                ExUserGroup exUserGroup = exUserGroups.get(userGroupIngDto.getResult_index());
                //设置关闭当前模块
                index=closeNowGroupGoNext(exUserGroups,userGroupIngDto.getResult_index(),exUserGroup,isSubmit);

//                //如果提交过了也不要重复提交
//                ExUserAnserQueryCriteria criteria=new ExUserAnserQueryCriteria();
//                criteria.setUserName(exUserGroup.getUserName());
//                criteria.setPublishPaperId(exUserGroup.getPublishPaperId());
//                criteria.setPublishGroupId(exUserGroup.getPublishGroupId());
//                List<ExUserAnser> exUserAnsers = exUserAnserService.queryAll(criteria);
//                if(UtilValidate.isEmpty(exUserAnsers)){
//                    //通知交卷
//                    exPublishPaperService.shoudongTongzhi(exUserGroup.getPublishPaperId());
//                }
            }else{
                //是否是从提交答案那边过来的
                if(isSubmit){
                    ExUserGroup exUserGroup = exUserGroups.get(userGroupIngDto.getIng_index());

                    //手动提交的 可以马上进行到下一个模块了
                    //设置关闭当前模块
                    index=closeNowGroupGoNext(exUserGroups,userGroupIngDto.getIng_index(),exUserGroup,isSubmit);
                }
            }

       }

        return index;
    }


    /**
     * 关闭当前模块 ，开启下一个模块
     */
    public Integer closeNowGroupGoNext(List<ExUserGroup> exUserGroups,Integer index,ExUserGroup exUserGroup,boolean isSubmit){
        //设置关闭当前模块
        log.info("----关闭当前模块:"+exUserGroup.getGroupName());
        exUserGroup.setStatus(2);
        saveOrUpdate(exUserGroup);
        //开启下一个模块
        if(index<exUserGroups.size()-1){
            //还有下一个模块 还能在开启
            index++;
            ExUserGroup next_group = exUserGroups.get(index);
            if(UtilValidate.isNotEmpty(next_group)&&next_group.getStatus()!=0){
                if(index<exUserGroups.size()-1){
                    //跳过
                    index++;
                    next_group = exUserGroups.get(index);
                }

            }
            if(UtilValidate.isNotEmpty(next_group)&&next_group.getStatus()==0){
                ExPublishGroup publishGroup = exPublishGroupService.getById(next_group.getPublishGroupId());
                Integer limitTime=publishGroup.getLimitTime();
                next_group.setStatus(1);
                log.info("----开启下一个模块:"+next_group.getGroupName());
                Date now=new Date();
                next_group.setStartTime(new Timestamp(now.getTime()));
                Date end_date = DateKit.dateAdd(6, now, limitTime);
                next_group.setEndTime(new Timestamp(end_date.getTime()));
                saveOrUpdate(next_group);
            }else{
                //没有下一个模块了，就不用管
            }
        }else{
            //这是最后一个模块了 考试结束
//            if(isSubmit){
//
//            }
        }
        return index;
    }

    /**
     *  是否到达时间点,不会进行下一模块的切换
     *
     * @param exUserGroups
     *  @return MAP() 'ing_index':0 正在进行的下标,'result_index':0 已到达时间的下标
     */
    @Override
    public UserGroupIngDto izArriveEndTime(List<ExUserGroup> exUserGroups) {

        Integer result=null;
        Integer index=null;
        for (int i = 0; i < exUserGroups.size(); i++) {
            ExUserGroup exUserGroup = exUserGroups.get(i);
            if(exUserGroup.getStatus()==1){
                index=i;
            }
        }
        if(index!=null){
            ExUserGroup exUserGroup = exUserGroups.get(index);

            // 判断当前时间是否已到达或超过结束时间
            if(exUserGroup.getStatus()==1){
                if(UtilValidate.isNotEmpty(exUserGroup.getEndTime())){
                    Date now = new Date();
                    Date endDate=new Date(exUserGroup.getEndTime().getTime());
                    if (now.after(endDate) || now.equals(endDate)) {
                        result=index;
                    }
                }else{
                    result=index;
                }

            }

        }
        UserGroupIngDto inDto=new UserGroupIngDto();
        inDto.setIng_index(index);
        inDto.setResult_index(result);

        return inDto;
    }
}
